<template>
  <div>
    <a-button type="link" @click.native="chat($event, owner)">
      {{ owner.name }}
    </a-button>
  </div>
</template>
<script>
import SockJS from "sockjs-client";
import { isEqual } from "lodash";
import ChatPanel from "./chat-panel.vue";
export default {
  name: "ChatBtn",
  components: { ChatPanel },
  props: {
    owner: {
      name: "",
      id: ""
    }
  },
  data() {
    return {
      user: {},
      panelVisible: false,
      sock: null
    };
  },
  watch: {
    "$store.state.login.user": {
      handler(nval) {
        this.user = nval;
      },
      deep: true
    }
  },
  methods: {
    chat(e, owner) {
      e.stopPropagation();
      if (isEqual(this.user, {})) {
        this.user = JSON.parse(sessionStorage.getItem("user"));
      }
      if (!this.user || isEqual(this.user, {})) {
        this.$store.commit("login/setModalVisible", { val: true });
      } else {
        this.$store.commit("chat/setVisible", { val: true });
        this.$store.commit("chat/setContactList", { val: owner });

        if (!global.sock) {
          global.sock = new SockJS(
            `${process.env.wsUrl}?receiveId=${owner.id}&sendId=${this.user.id}`
          );
          global.sock.onopen = () => {
            this.panelVisible = true;
          };
          global.sock.onmessage = function(e) {
            console.log("message", e.data);
          };
        }

        // global.sock.onclose = function() {
        //   console.log("close");
        // };
      }
    }
  }
};
</script>
<style lang="less" scoped></style>
